﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PCCardM.UIControl;
using PCCardM.Basic;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Configuration;
using DevComponents.DotNetBar.Controls;

namespace PCCardN
{
    public partial class Frm_DataBase : Form
    {
        private SqlConnection conn;
        private SqlCommand cmd;
        private bool connected = false;
        //配置参数
        ConfigSet config = new ConfigSet();

        public Frm_DataBase()
        {
            InitializeComponent();
            //初始化使用数据库类型
            //初始化中心数据参数
            IniDBConfigPar("SqlConnStringCenter");
        }

        /// <summary>
        /// 初始化配置参数
        /// </summary>
        private void IniDBConfigPar(string Ref_Type)
        {
            //取得配置文件中数据库信息
            string strconn = Properties.Settings.Default.ConnString;
            SetIniDataPar(strconn, comboB_DBServer, comboB_DBLoginName, comboB_DBPwd, comboB_DBName);

        }
        /// <summary>
        /// 设置参数
        /// </summary>
        /// <param name="strconn"></param>
        /// <param name="DBServer"></param>
        /// <param name="DBLoginName"></param>
        /// <param name="DBPwd"></param>
        /// <param name="DBName"></param>
        private void SetIniDataPar(string strconn, ComboBoxEx DBServer, ComboBoxEx DBLoginName, TextBoxEx DBPwd, ComboBoxEx DBName)
        {
            if (!string.IsNullOrEmpty(strconn))
            {
                string[] strItems = strconn.Split(";".ToCharArray());
                if (strItems.Length > 0)
                {
                    for (int i = 0; i < strItems.Length; i++)
                    {
                        if (strItems[i].IndexOf("server=") != -1)
                        {
                            DBServer.Text = strItems[i].Replace("server=", "");
                        }
                        if (strItems[i].IndexOf("uid=") != -1)
                        {
                            DBLoginName.Text = strItems[i].Replace("uid=", "");
                        }
                        if (strItems[i].IndexOf("pwd=") != -1)
                        {
                            DBPwd.Text = strItems[i].Replace("pwd=", "");
                        }
                        if (strItems[i].IndexOf("database=") != -1)
                        {
                            DBName.Text = strItems[i].Replace("database=", "");
                        }
                    }
                }
            }
        }
        #region 1.获取数据库
        /// <summary>
        /// 拼接连接字符串
        /// </summary>
        /// <returns></returns>
        private SqlConnection GetConnection()
        {
            SqlConnection conn = new SqlConnection();

            conn.ConnectionString = "server=" + this.comboB_DBServer.Text.Trim() + ";database=master;uid=" + this.comboB_DBLoginName.Text.Trim() + ";pwd=" + this.comboB_DBPwd.Text.Trim();

            return conn;
        }
        #endregion 获取数据库

        #region 2.测试数据库
        /// <summary>
        /// 测试数据库连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_DBTest_Click(object sender, EventArgs e)
        {
            //测试
            if (CheckDBSet(comboB_DBServer.Text.Trim(), comboB_DBLoginName.Text.Trim(), comboB_DBPwd.Text.Trim()))
            {
                getDBTest();
            }

        }

        private bool CheckDBSet(string DBServer, string DBLoginName, string DBPwd)
        {
            bool check = false;
            Match ma = Regex.Match(this.comboB_DBServer.Text, @"((?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d))");
            if (string.IsNullOrEmpty(DBServer))
            {
                MessageBoxEx.ShowMessage("请填写数据库服务!", MessageKind.Information);
                comboB_DBServer.Focus();
                check = false;
            }
            else if (string.IsNullOrEmpty(DBLoginName))
            {
                MessageBoxEx.ShowMessage("请填写数据库登录名!", MessageKind.Warning);
                comboB_DBLoginName.Focus();
                check = false;
            }
            else if (string.IsNullOrEmpty(DBPwd))
            {
                MessageBoxEx.ShowMessage("请填写数据库库密码!", MessageKind.Warning);
                comboB_DBPwd.Focus();
                check = false;
            }
            else
            {
                check = true;
            }
            return check;
        }
        /// <summary>
        /// 测试连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void getDBTest()
        {
            conn = GetConnection();
            try
            {
                SqlHelper sql = new SqlHelper();
                conn.Open();
                cmd = new SqlCommand("select name from master..sysdatabases", conn);
                DataTable dt = new DataTable();
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                adapter.Fill(dt);
                conn.Close();
                connected = true;
                this.Cursor = Cursors.Default;
                MessageBoxEx.ShowMessage("连接测试成功!", MessageKind.Warning);
                this.comboB_DBName.DataSource = dt;
                this.comboB_DBName.DisplayMember = "name";
                bt_DBSave.Enabled = true;
            }
            catch (InvalidOperationException)
            {
                this.Cursor = Cursors.Default;
                MessageBoxEx.ShowMessage("无法连接到指定数据库服务器!", MessageKind.Warning);
                this.comboB_DBName.Text = "";
                bt_DBSave.Enabled = false;
                bt_DBTest.Enabled = true;
            }
            catch (SqlException ex)
            {
                this.Cursor = Cursors.Default;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < ex.Errors.Count; i++)
                    sb.Append(ex.Errors[i].Message).Append(Environment.NewLine);
                MessageBoxEx.ShowMessage("连接数据库出错：" + Environment.NewLine + sb.ToString(), MessageKind.Warning);
                this.comboB_DBName.Text = "";
                bt_DBSave.Enabled = false;
                bt_DBTest.Enabled = true;
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Default;
                MessageBoxEx.ShowMessage("出现意外错误：" + Environment.NewLine + ex.Message, MessageKind.Warning);
                this.comboB_DBName.Text = "";
                bt_DBSave.Enabled = false;
                bt_DBTest.Enabled = true;
            }
            finally
            {
                this.Cursor = Cursors.Default;
                if (conn.State != ConnectionState.Closed)
                    conn.Close();
            }
        }
        #endregion 测试数据库

        #region 3.保存数据库
        private void bt_DBSave_Click(object sender, EventArgs e)
        {
            SaveDB();
        }
        private void SaveDB()
        {

            if (CheckDBSet(comboB_DBServer.Text.Trim(), comboB_DBLoginName.Text.Trim(), comboB_DBPwd.Text.Trim()))
            {
                if (string.IsNullOrEmpty(comboB_DBName.Text.Trim()))
                {
                    MessageBoxEx.ShowMessage("请填写数据库库名称!", MessageKind.Warning);
                    comboB_DBName.Focus();
                    return;
                }
                try
                {
                    string SqlConnString = "server=" + this.comboB_DBServer.Text.Trim() + ";uid=" + this.comboB_DBLoginName.Text.Trim() + ";pwd=" + this.comboB_DBPwd.Text.Trim() + ";database=" + this.comboB_DBName.Text.Trim() + "";
                    Properties.Settings.Default.ConnString= SqlConnString;
                    Properties.Settings.Default.Save();
                    MessageBox.Show("已保存数据库配置！");
                }
                catch (Exception ex)
                {
                    MessageBoxEx.ShowMessage("保存数据库参数失败：" + Environment.NewLine + ex.Message, MessageKind.Warning);
                }
            }


        }
        #endregion 保存数据库

        #region 4.退出数据库
        private void bt_DBExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion 退出数据库


        /// <summary>
        /// 选择数据库
        /// </summary>
        private void SelectDB(ComboBoxEx cmb, string Ref_Type)
        {
            if (connected)
            {
                this.Cursor = Cursors.WaitCursor;
                cmb.Items.Clear();
                conn = GetConnection();
                try
                {
                    conn.Open();
                    cmd = new SqlCommand("select name from master..sysdatabases", conn);
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                        cmb.Items.Add(reader["name"]);
                    reader.Close();
                    conn.Close();
                    connected = true;
                    this.Cursor = Cursors.Default;
                }
                catch (InvalidOperationException)
                {
                    this.Cursor = Cursors.Default;
                    MessageBoxEx.ShowMessage("无法连接到指定数据库服务器", MessageKind.Information);
                    cmb.Text = "";
                }
                catch (SqlException ex)
                {
                    this.Cursor = Cursors.Default;
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < ex.Errors.Count; i++)
                        sb.Append(ex.Errors[i].Message).Append(Environment.NewLine);
                    MessageBoxEx.ShowMessage("连接数据库出错：" + Environment.NewLine + sb.ToString(), MessageKind.Information);
                    cmb.Text = "";
                }
                catch (Exception ex)
                {
                    this.Cursor = Cursors.Default;
                    MessageBoxEx.ShowMessage("出现意外错误：" + Environment.NewLine + ex.Message, MessageKind.Information);
                    cmb.Text = "";
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                    if (conn.State != ConnectionState.Closed)
                        conn.Close();
                }
            }
            else
            {
                this.Cursor = Cursors.Default;
                MessageBoxEx.ShowMessage("请先配置连接参数或测试连接", MessageKind.Information);
                cmb.Text = "";
            }
        }



    }
}
